package com.example.service.impl;

import com.example.entity.InStore;
import com.example.entity.Product;
import com.example.entity.Result;
import com.example.mapper.BuyListMapper;
import com.example.mapper.InStoreMapper;
import com.example.mapper.ProductMapper;
import com.example.page.Page;
import com.example.service.InStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author:tjf
 * @Description:
 */
@Service
public class InStoreServiceImpl implements InStoreService {
    @Autowired
    private InStoreMapper inStoreMapper;
    @Autowired
    private BuyListMapper buyListMapper;
    @Autowired
    private ProductMapper productMapper;

    /**
     * 生成入库单的业务方法
     *
     * @param inStore
     * @param buyListId
     * @return
     */
    @Transactional
    @Override
    public Result saveInStore(InStore inStore, Integer buyListId) {
        // 持久化生成的入库单
        if (inStoreMapper.insertInStore(inStore) > 0) {
            // 修改采购单的is_in为已入库
            if (buyListMapper.updateBuyListIsInById(buyListId) > 0) {
                return Result.ok("入库单已生成！");
            }
            return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");
        }
        return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");    }

    /**
     * 根据条件查询入库单并分页的业务方法
     * @param inStore
     * @param page
     */
    @Override
    public void queryInStoreByConditionForPagination(InStore inStore, Page page) {
        // 根据条件查询入库单的数量
        int inStoreCount = inStoreMapper.selectInStoreCountByCondition(inStore);

        // 根据条件，查询入库单并分页
        List<InStore> inStoreList = inStoreMapper.selectInStoreByConditionForPagination(inStore, page);

        // 封装参数page
        page.setTotalNum(inStoreCount);
        page.setResultList(inStoreList);
    }

    /**
     * 确定入库的业务方法
     * @param inStore
     * @param updateBy
     * @return
     */
    @Transactional
    @Override
    public Result confirmInStore(InStore inStore, Integer updateBy) {
        //1 确认入库
        if (inStoreMapper.updateInStoreById(inStore) <= 0) {// 入库失败
            return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");
        }

        // 入库成功
        //2 修改当前入库商品的库存量
        Product product = productMapper.selectProductById(inStore.getProductId());

        // 修改product对象的数据(updateBy, productInvent)
        product.setUpdateBy(updateBy);
        product.setProductInvent(product.getProductInvent() + inStore.getInNum());

        // 修改productId对应的记录的库存
        if (productMapper.updateProductById(product) <= 0) {
            return Result.err(Result.CODE_ERR_SYS, "系统忙，请稍后重试！");
        }

        return Result.ok("入库成功！");
    }
}
